package com.samebuilding.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.samebuilding.dao.FansRequestDAO;
import com.samebuilding.domain.FansRequest;
import com.samebuilding.domain.User;

public class FansRequestDAOImpl  extends GenericDAOImpl<FansRequest, Integer>
		implements FansRequestDAO {

	private static final String DELETE_BY_UID = "delete from FansRequest where sendUserNo = ? and receiveUserNo = ?";
	private static final String GET_BY_RECEIVE_UID = "select u from FansRequest as fr, User as u where fr.receiveUserNo = ? and fr.sendUserNo = u.userNo";
	private static final String GET_COUNT_BY_RECEIVE_UID = "select count(*) from FansRequest fr where fr.receiveUserNo = ?";
	private static final String IS_SEND_CONTAIN_RECEIVE = "from FansRequest where sendUserNo = ? and receiveUserNo = ?";
	
	
	public void delByUid(final int sendUid, final int receiveUid) {
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(DELETE_BY_UID);
				query.setInteger(0, sendUid);
				query.setInteger(1, receiveUid);
				query.executeUpdate();
				return null;
			}
		});

	}

	@SuppressWarnings("unchecked")
	public List<User> getByReceiveUid(final int receiveUid, final int startRecord, final int maxRecord) {
		return (List<User>)getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(GET_BY_RECEIVE_UID);
				query.setInteger(0, receiveUid);
				query.setFirstResult(startRecord);
				query.setMaxResults(maxRecord);
				List<User> list = query.list();
				return list;
			}
		});
	}

	public int getCountByReceiveUid(final int receiveUid) {
		long count = (Long)this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(GET_COUNT_BY_RECEIVE_UID);
				query.setInteger(0, receiveUid);

				return query.uniqueResult();
			}
		});
		return (int)count;
	}

	public boolean isSendUidContainReceiveUid(final int sendUid,final int receiveUid) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(IS_SEND_CONTAIN_RECEIVE);
				query.setInteger(0, sendUid);
				query.setInteger(1, receiveUid);
				List list = query.list();
				return list;
			}
		});
		if(list == null || list.size() == 0) {
			return false;
		} else {
			return true;
		}
	}

}
